<?php

namespace addons\xykeep\listener;

use addons\xykeep\service\Distribution as DistributionService;
use addons\xykeep\service\distribution\Commission;
use app\common\model\CouponsOrder as CouponsOrderModel;
use app\common\model\SettledOrder as SettledOrderModel;

/**
 * 分销钩子处理
 */
class Distribution
{

    // 订单支付成功 
    public function xykeepOrderPayedAfter(&$params){

        $orderData = $params['order'];
        $orderType = $params['type'];  // 订单类型 course=课程 vip=会员卡 ...

        // 重新查询订单
        $order = null;

        // 信息券
        if ($orderType == 'coupons') {
            $order = CouponsOrderModel::where(['id'=>$orderData['id']])->find();
        }

        // 教师入驻
        if ($orderType == 'settled') {
            $order = SettledOrderModel::where(['id'=>$orderData['id']])->find();
        }


        if (!$order) return false;

        $distributon = new DistributionService($order['user_id']);

        if (!$distributon->user)  return false;

        // 加用户消费金额
        if ($order['total_fee'] > 0) {
            $distributon->user->setInc('xykeep_consume', $order['total_fee']);
        }

        // 绑定关系
        $distributon->bindUserRelation('pay');
        

        // 记录、处理分佣升级
        $commission = new Commission($order,$orderType);
        // 检查能否分销
        if ($commission->checkAndSetCommission()) {
            // 添加分销订单
            $distributionOrder = $commission->addDistributionOrder();
            // 支付后分佣
            $cm = $commission->grantDistributionOrder('payed', $distributionOrder->id);

            if($cm && in_array($orderType, ['vip','course'])){
                // 添加门店收入和记录(减掉佣金)
                $storeService =  new StoreService($order['store_id']);
                $mt = 'vip_commission';
                if($orderType == 'course'){
                    $mt = 'course_commission';
                }
                $storeService->money(-$cm,$mt,$order['id']);
            }
        }
    }
    
    /**
     * 用户注册账号之后，添加分销账号
     */
    public function xykeepRegisterAfter($user){
        if($user){
            $distribution = new DistributionService($user->id);
            $distribution->becomeDistribution();
        }
    }

    /**
     * 用户通过分享进入后,绑定用户上级
     */
    public function xykeepShareAfter($shareLog){
        if ($shareLog) {
            $user_id = intval($shareLog->user_id); // 受邀用户
            $share_id = intval($shareLog->share_id); // 邀请人

            $distribution = new DistributionService($user_id);
            $distribution->bindUserRelation('share', $share_id); //绑定关系
            
        }
    }
    
}
